﻿Namespace MediaInfoDll
    Public Class Manager
        Public Shared Function GetStreamInfo(ByVal files As Generic.List(Of String)) As Entities.OpenMediaInfo.StreamInfo
            Return GetStreamInfo(files.ToArray)
        End Function
        Public Shared Function GetStreamInfo(ByVal files() As String) As Entities.OpenMediaInfo.StreamInfo
            Dim clsRet As New Entities.OpenMediaInfo.StreamInfo
            clsRet.VideoStreams = New Generic.List(Of Entities.OpenMediaInfo.VideoStreamInfo)
            clsRet.AudioStreams = New Generic.List(Of Entities.OpenMediaInfo.AudioStreamInfo)
            clsRet.SubtitleStreams = New Generic.List(Of Entities.OpenMediaInfo.SubtitleStreamInfo)

            Dim strIdxFileToAnalyze As String = Nothing
            Dim strMainFileName As String = Nothing
            Dim blnHasLoadedSub As Boolean = False
            For Each strFilename As String In files
                If Not strFilename.ToLower.EndsWith(".srt") Then
                    strMainFileName = IO.Path.GetFileNameWithoutExtension(strFilename)
                    Exit For
                End If
            Next

            For Each strFilename As String In files
                If strFilename.ToLower.EndsWith(".omx") Then
                    'skip this file
                ElseIf strFilename.ToLower.EndsWith(".idx") Then
                    strIdxFileToAnalyze = strFilename
                ElseIf strFilename.ToLower.EndsWith(".srt") Then
                    AddTextTrack(strFilename, clsRet, strMainFileName)
                Else
                    Dim clsMI As New MediaInfoDll.MediaInfo

                    clsMI.Open(strFilename)
                    Try
                        Dim strDuration As String = clsMI.Get_(MediaInfoDll.StreamKind.General, 0, "Duration/String")
                        If Not String.IsNullOrEmpty(strDuration) Then clsRet.Runtime = strDuration
                        Dim strBitrate As String = clsMI.Get_(MediaInfoDll.StreamKind.General, 0, "OverallBitRate/String")
                        If Not String.IsNullOrEmpty(strBitrate) Then clsRet.OverallBitrate = strBitrate

                        AddVideoTracks(clsMI, clsRet)
                        AddAudioTracks(clsMI, clsRet)
                        AddTextTracks(clsMI, clsRet)

                        If strFilename.ToLower.EndsWith(".sub") Then blnHasLoadedSub = True
                    Finally
                        clsMI.Close()
                    End Try
                End If
            Next
            If blnHasLoadedSub And Not String.IsNullOrEmpty(strIdxFileToAnalyze) Then
                AddInfoFromIdxFile(strIdxFileToAnalyze, clsRet)
            End If

            Return clsRet
        End Function

        Private Shared Sub AddInfoFromIdxFile(ByVal idxFileToAnalyze As String, ByVal streamInfo As Entities.OpenMediaInfo.StreamInfo)
            Dim aLangs As New Generic.List(Of String)
            Using tr As New System.IO.StreamReader(idxFileToAnalyze)
                While Not tr.EndOfStream
                    Dim strLine As String = tr.ReadLine()
                    'id: sv, index: 15
                    If strLine.ToLower.StartsWith("id: ") AndAlso strLine.ToLower.IndexOf("index:") > 0 Then
                        Dim aParts() As String = strLine.Split(" "c)
                        Dim strLang As String = aParts(1)
                        If strLang.EndsWith(","c) Then strLang = strLang.Substring(0, strLang.Length - 1)
                        aLangs.Add(strLang)
                    End If
                End While
            End Using

            If aLangs.Count = streamInfo.SubtitleStreams.Count Then
                For i As Integer = 0 To aLangs.Count - 1
                    streamInfo.SubtitleStreams(i).Language = aLangs(i)
                Next
            End If
        End Sub

        Private Shared Sub AddVideoTracks(ByVal mi As MediaInfoDll.MediaInfo, ByVal streamInfo As Entities.OpenMediaInfo.StreamInfo)
            Dim iTrackCount As Integer = mi.Count_Get(MediaInfoDll.StreamKind.Visual)

            For i As Integer = 0 To iTrackCount - 1
                Dim clsTrack As New Entities.OpenMediaInfo.VideoStreamInfo
                clsTrack.Id = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "ID")

                clsTrack.Format = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Format")
                clsTrack.FormatInfo = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Format/Info")
                clsTrack.FormatProfile = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Format_Profile")

                clsTrack.Bitrate = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "BitRate/String")
                clsTrack.BitrateMode = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "BitRate_Mode/String")

                clsTrack.Width = CInt(mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Width"))
                clsTrack.Height = CInt(mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Height"))
                clsTrack.AspectRatio = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "DisplayAspectRatio")
                clsTrack.Framerate = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "FrameRate/String")
                clsTrack.BitsPerPixelFrame = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Bits-(Pixel*Frame)")

                clsTrack.Language = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Language/String")
                clsTrack.LanguageInfo = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "Language_More")

                If String.IsNullOrEmpty(clsTrack.Bitrate) Then
                    clsTrack.Bitrate = mi.Get_(MediaInfoDll.StreamKind.Visual, i, "BitRate_Nominal/String")
                End If

                streamInfo.VideoStreams.Add(clsTrack)
            Next
        End Sub

        Private Shared Sub AddAudioTracks(ByVal mi As MediaInfoDll.MediaInfo, ByVal streamInfo As Entities.OpenMediaInfo.StreamInfo)
            Dim iTrackCount As Integer = mi.Count_Get(MediaInfoDll.StreamKind.Audio)

            For i As Integer = 0 To iTrackCount - 1
                Dim clsTrack As New Entities.OpenMediaInfo.AudioStreamInfo
                clsTrack.Id = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "ID")

                clsTrack.Format = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Format")
                clsTrack.FormatInfo = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Format/Info")
                clsTrack.FormatProfile = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Format_Profile")

                clsTrack.Bitrate = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "BitRate/String")
                clsTrack.BitrateMode = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "BitRate_Mode/String")

                clsTrack.Channels = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Channel(s)/String")
                clsTrack.ChannelPositions = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "ChannelPositions/String2")

                clsTrack.Language = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Language/String")
                clsTrack.LanguageInfo = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "Language_More")

                If String.IsNullOrEmpty(clsTrack.Bitrate) Then
                    clsTrack.Bitrate = mi.Get_(MediaInfoDll.StreamKind.Audio, i, "BitRate_Nominal/String")
                End If

                streamInfo.AudioStreams.Add(clsTrack)
            Next
        End Sub

        Private Shared Sub AddTextTracks(ByVal mi As MediaInfoDll.MediaInfo, ByVal streamInfo As Entities.OpenMediaInfo.StreamInfo)
            Dim iTrackCount As Integer = mi.Count_Get(MediaInfoDll.StreamKind.Text)

            For i As Integer = 0 To iTrackCount - 1
                Dim clsTrack As New Entities.OpenMediaInfo.SubtitleStreamInfo
                clsTrack.Id = mi.Get_(MediaInfoDll.StreamKind.Text, i, "ID")

                clsTrack.Format = mi.Get_(MediaInfoDll.StreamKind.Text, i, "Format")
                clsTrack.FormatInfo = mi.Get_(MediaInfoDll.StreamKind.Text, i, "Format/Info")

                clsTrack.Language = mi.Get_(MediaInfoDll.StreamKind.Text, i, "Language/String")
                clsTrack.LanguageInfo = mi.Get_(MediaInfoDll.StreamKind.Text, i, "Language_More")

                streamInfo.SubtitleStreams.Add(clsTrack)
            Next
        End Sub

        Private Shared Sub AddTextTrack(ByVal srtFileName As String, ByVal streamInfo As Entities.OpenMediaInfo.StreamInfo, ByVal mainFileName As String)
            Try
                Dim clsTrack As New Entities.OpenMediaInfo.SubtitleStreamInfo
                clsTrack.Format = "SRT"

                Dim strTmp As String = IO.Path.GetFileNameWithoutExtension(srtFileName).ToLower
                If strTmp = mainFileName.ToLower Or mainFileName.Length > strTmp.Length Then
                    Dim udtLanguage As Framework.TextLanguageAnalysis.Language
                    udtLanguage = Framework.TextLanguageAnalysis.GetLanguageOfFile(srtFileName)
                    Select Case udtLanguage
                        Case Framework.TextLanguageAnalysis.Language.Unknown
                            clsTrack.Language = String.Empty
                        Case Else
                            clsTrack.Language = udtLanguage.ToString
                    End Select
                ElseIf strTmp.StartsWith(mainFileName) Then
                    clsTrack.Language = strTmp.Substring(mainFileName.Length + 1)
                Else
                    Dim udtLanguage As Framework.TextLanguageAnalysis.Language
                    udtLanguage = Framework.TextLanguageAnalysis.GetLanguageOfFile(srtFileName)
                    Select Case udtLanguage
                        Case Framework.TextLanguageAnalysis.Language.Unknown
                            clsTrack.Language = String.Empty
                        Case Else
                            clsTrack.Language = udtLanguage.ToString
                    End Select
                End If
                streamInfo.SubtitleStreams.Add(clsTrack)
            Catch ex As Exception
                Throw New Exception(String.Format("Failed adding texttrack for srtfile ""{0}"" for mainfile ""{2}""! ({1})", srtFileName, ex.Message, mainFileName))
            End Try
        End Sub
    End Class
End Namespace